package com.zy.io;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Gong
 * @Description
 * @dATE 2021/12/12 14:42
 **/
public class ObjectStreamTest {
    public static void main(String[] args) {
        ObjectStreamTest t = new ObjectStreamTest();
        t.read();

    }
    //序列化对象
    public  void write() {
        List<User> list = new ArrayList<User>();
        list.add(new User(1, "aa"));
        list.add(new User(2, "bb"));
        list.add(new User(3, "cc"));
        User u = new User(4, "wyl", list);
        File file = new File("d:/temp/user.dat");
        FileOutputStream out = null;
        ObjectOutputStream obj = null;
        try {
            out=new FileOutputStream(file);
            obj=new ObjectOutputStream(out);
            obj.writeObject(u);
            System.out.println("保存成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (obj != null){
                    obj.close();
                }

                if (out != null){
                    out.close();
                }

            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
    public  void read() {
        User user=null;
        File file=new File("d:/temp/user.dat");
        FileInputStream in=null;
        ObjectInputStream obj=null;
        try {
            in=new FileInputStream(file);
            obj=new ObjectInputStream(in);
            user=(User) obj.readObject();
            user.print();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (obj != null){
                    obj.close();
                }

                if (in != null){
                    in.close();
                }

            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

    }

}
